<template>
    <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="合同标题">
            <el-input v-model="form.title" placeholder="请输入合同标题" clearable />
        </el-form-item>
        <el-form-item label="货主单位">
            <el-select v-model="form.flatsName" style="width: 150px;" placeholder="请输入货主单位" clearable>
                <el-option v-for="item in owners" :label="item.flatsName" :value="item.flatsName" />
            </el-select>
        </el-form-item>
        <el-form-item label="货主负责人">
            <el-select v-model="form.ownerName" style="width: 150px;" placeholder="请输入货主负责人" clearable>
                <el-option v-for="item in owners" :label="item.ownerName" :value="item.ownerName" />
            </el-select>
        </el-form-item>
        <el-form-item label="经办人">
            <el-select v-model="form.ownerName" style="width: 150px;" placeholder="请输入经办人" clearable>
                <el-option v-for="item in owners" :label="item.ownerName" :value="item.ownerName" />
            </el-select>
        </el-form-item>
        <el-form-item label="签订时间">
            <el-date-picker v-model="form.date" type="date" placeholder="Pick a date" clearable />
        </el-form-item>
        <el-form-item label="审批状态">
            <el-select v-model="form.state" style="width: 150px;" placeholder="请输入审批状态" clearable>
                <el-option label="待提交" value="待提交" />
                <el-option label="待审核" value="待审核" />
                <el-option label="已通过" value="已通过" />
                <el-option label="已拒绝" value="已拒绝" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getownercontract()">查询</el-button>
        </el-form-item>
    </el-form>
    <el-button type="primary" @click="addownercontract()">新增</el-button>

    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="ownerContractNumber" label="合同编号" width="180" />
        <el-table-column prop="ownerContractTitle" label="合同标题" width="180" />
        <el-table-column prop="flatsName" label="货主单位" />
        <el-table-column prop="ownerName" label="货主负责人" />
        <el-table-column prop="lineName" label="线路" />
        <el-table-column prop="tonFreightPrice" label="吨运价" />
        <el-table-column prop="charterTonnage" label="包车条件吨位" />
        <el-table-column prop="charterPrice" label="包车金额" />
        <el-table-column prop="signedDate" label="签订日期">
            <template v-slot="scope">
                <span>{{ scope.row.signedDate.substring(0, 10) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="handlerName" label="经办人" />
        <el-table-column prop="createDate" label="创建时间" />
        <el-table-column prop="ownerContractState" label="状态">
            <template v-slot="scope">
                <span v-if="scope.row.ownerContractState === 1">待提交</span>
                <span v-else-if="scope.row.ownerContractState === 2">待审批</span>
                <span v-else-if="scope.row.ownerContractState === 3">已通过</span>
                <span v-else-if="scope.row.ownerContractState === 4">已拒绝</span>
            </template>
        </el-table-column>
        <el-table-column prop="approvalName" label="审批人" />
        <el-table-column fixed="right" label="操作" min-width="120">
            <template v-slot="scope" #default>
                <el-button link type="primary" @click="deleteownercontract(scope.row.ownerContractId)">
                    删除
                </el-button>
                <el-button link type="primary" v-if="scope.row.ownerContractState == 1"
                    @click="addownerapproval(scope.row)">提交审批</el-button>
                <el-button link type="primary" v-else-if="scope.row.ownerContractState === 2"> </el-button>
                <el-button link type="primary" v-else-if="scope.row.ownerContractState === 3"> </el-button>
                <el-button link type="primary" v-else-if="scope.row.ownerContractState === 4"
                    @click="addownerapproval(scope.row)">重新提交</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize"
        :page-sizes="[10, 15, 20, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
        :total="page.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <el-dialog v-model="dialogVisible" title="新增">
        <template #footer>
            <div class="dialog-footer">
                <el-form ref="ruleFormRef" :inline="true" :model="form1" :rules="rules" status-icon
                    class="demo-form-inline">
                    <el-form-item label="合同标题" prop="ownerContractTitle" style="width: 240px;">
                        <el-input v-model="form1.ownerContractTitle" />
                    </el-form-item>
                    <el-form-item label="货主单位" prop="flatsName" style="width: 240px;">
                        <el-select v-model="form1.flatsName" placeholder="请选择货主单位" clearable>
                            <el-option v-for="item in owners" :label="item.flatsName" :value="item.flatsName" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="货主负责人" prop="ownerName" style="width: 240px;">
                        <el-select v-model="form1.ownerName" placeholder="请选择货主单位" clearble>
                            <el-option v-for="item in owners" :label="item.ownerName" :value="item.ownerName" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="线路" prop="lineName" style="width: 240px;">
                        <el-select v-model="form1.lineName" placeholder="请选择线路" clearable>
                            <el-option v-for="item in lines" :label="item.line_Name" :value="item.line_Name" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="吨 运 价" prop="tonFreightPrice" style="width: 240px;">
                        <el-input v-model="form1.tonFreightPrice" />
                    </el-form-item>
                    <el-form-item label="包车条件吨位" prop="name" style="width: 240px;">
                        <el-input v-model="form1.charterTonnage" />
                    </el-form-item>
                    <el-form-item label="包车金额" prop="name" style="width: 240px;">
                        <el-input v-model="form1.charterPrice" />
                    </el-form-item>
                    <el-form-item label="经办人" prop="handlerName" style="width: 240px;">
                        <el-select v-model="form1.handlerName" placeholder="请选择货主单位" clearable>
                            <el-option v-for="item in owners" :label="item.ownerName" :value="item.ownerName" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="签订时间" prop="signedDate" style="width: 240px;">
                        <el-date-picker v-model="form1.signedDate" type="date" placeholder="Pick a date" clearable />
                    </el-form-item>
                    <el-form-item label="合同金额" prop="name" style="width: 240px;">
                        <el-input v-model="form1.ownerContractPrice" />
                    </el-form-item>
                    <el-form-item label="合同标的或项目说明" prop="name" style="width: 550px;">
                        <el-input v-model="form1.ownerContractContent" type="textarea" />
                    </el-form-item>
                    <el-form-item label="合同主要条款/变更条款" prop="name" style="width: 550px;">
                        <el-input v-model="form1.ownerContractAlter" type="textarea" />
                    </el-form-item>
                    <el-form-item label="合同文本（附件）" prop="name" style="width: 550px;">
                        <el-upload v-model:file-list="form1.ownerContractText" class="upload-demo"
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" multiple
                            :on-preview="handlePreview" :on-remove="handleRemove" :limit="3"
                            :before-remove="beforeRemove" :on-exceed="handleExceed">
                            <el-button type="primary">上传文件</el-button>
                        </el-upload>
                    </el-form-item><br>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleFormRef, 2)">
                            提交审批
                        </el-button>

                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef, 1)">
                            保存草稿
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import axios from '@/api/http'

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

//对话框
const dialogVisible = ref(false)

const form = reactive({
    title: '',
    flatsName: '',
    ownerName: '',
    handlerName: '',
    date: '',
    state: 0,
    pageIndex: 1,
    pageSize: 10,

})
//多选框
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}

const form1 = reactive({
    "ownerContractNumber": "",
    "ownerContractTitle": "",
    "flatsName": "",
    "ownerName": "",
    "lineName": "",
    "tonFreightPrice": '',
    "charterTonnage": '',
    "charterPrice": '',
    "signedDate": "2024-08-28",
    "handlerName": "",
    "ownerContractPrice": '',
    "ownerContractContent": "",
    "ownerContractAlter": "",
    "ownerContractText": "",
    "createName": "",
    "createDate": "2024-08-28",
    "updateName": "",
    "updateTime": "2024-08-28",
    "ownerContractState": 0,
    "approvalName": "",
})

const page = reactive({
    total: 0,
    totalPage: 0,
})
//显示列表
const tableData = ref([])
const getownercontract = () => {
    axios.post('/contract/api/ownercontract/Getownercontract', form)
        .then(res => {
            tableData.value = res.data
            page.total = res.total
            page.totalPage = res.totalPage
        })
}

//分页方法
const handleSizeChange = (val: number) => {
    form.pageSize = val
    getownercontract()
}
const handleCurrentChange = (val: number) => {
    form.pageIndex = val
    getownercontract()
}
//货主下拉框方法
const owners: any = ref([])
const getowner = async () => {
    axios.get('/contract/api/ownercontract/Getowner')
        .then(res => {
            owners.value = res
        })
}
//线路下拉框方法
const lines: any = ref([])
const getline = async () => {
    axios.get('/contract/api/ownercontract/GetLines')
        .then(res => {
            lines.value = res
        })
}
//新增弹框
const addownercontract = () => {
    dialogVisible.value = true;
}

//验证
const rules = reactive<FormRules<RuleForm>>({
    ownerContractTitle: [
        { required: true, message: '请输入合同标题', trigger: 'blur' },
    ],
    flatsName: [
        { required: true, message: '请输入货主单位', trigger: 'blur' },
    ],
    ownerName: [
        { required: true, message: '请输入货主负责人', trigger: 'blur' },
    ],
    lineName: [
        { required: true, message: '请选择线路', trigger: 'blur' },
    ],
    tonFreightPrice: [
        { required: true, message: '请输入吨运价', trigger: 'blur' },
    ],
    handlerName: [
        { required: true, message: '请选择经办人', trigger: 'blur' },
    ],
    signedDate: [
        { required: true, message: '请选择签订时间', trigger: 'blur' },
    ],
})

//新增
const submitForm = async (formEl: FormInstance | undefined, state: any) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post('/contract/api/ownercontract/AddOwnercontract?state=' + state, form1)
                .then(res => {
                    if (res > 0) {
                        ElMessage.success('新增成功')
                        getownercontract();

                    } else {
                        ElMessage.error('新增失败')
                        getownercontract();
                    }
                    dialogVisible.value = false
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}
//清空
const resetForm = () => {
    dialogVisible.value = false
}
//上传文件
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
    console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile)
}


const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.warning(
        `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
        } totally`
    )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `Cancel the transfer of ${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    )
}
//删除
const deleteownercontract = async (id: any) => {
    ElMessageBox.confirm(
        '您确定要删除吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post('/contract/api/ownercontract/DeleteOwnercontract?ownercontractid=' + id)
                .then(res => {
                    if (res > 0) {
                        ElMessage.success('删除成功')
                        getownercontract()
                    }
                    else {
                        ElMessage.error('删除失败')
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
//提交审批
const addownerapproval = (row: any) => {
    const rows = reactive({
        "ownerContractId": row.ownerContractId,
        "ownerContractNumber": row.ownerContractNumber,
        "ownerContractTitle": row.ownerContractTitle,
        "flatsName": row.flatsName,
        "ownerName": row.ownerName,
        "lineName": row.lineName,
        "tonFreightPrice": row.tonFreightPrice,
        "charterTonnage": row.charterTonnage,
        "charterPrice": row.charterPrice,
        "signedDate": row.signedDate,
        "handlerName": row.handlerName,
        "ownerContractPrice": row.ownerContractPrice,
        "ownerContractContent": row.ownerContractContent,
        "ownerContractAlter": row.ownerContractAlter,
        "ownerContractText": row.ownerContractText,
        "createName": row.createName,
        "createDate": row.createDate,
        "updateName": row.updateName,
        "updateTime": row.updateTime,
        "ownerContractState": row.ownerContractState,
        "approvalName": row.approvalName,
        "isDel": row.isDel,
    })
    console.log(rows)
    ElMessageBox.confirm(
        '您确定要提交审批吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post('/contract/api/ownercontract/Addownerapproval?state=' + rows.ownerContractState, rows)
                .then(res => {
                    if (res > 0) {
                        ElMessage.success('提交成功')
                        getownercontract()
                    }
                    else {
                        ElMessage.error('提交失败')
                        getownercontract()
                    }
                })
        })
        .catch(() => {

        })
}


onMounted(() => {
    getownercontract()
    getowner()
    getline()
})

</script>